using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using DesktopHelper.Services;

namespace DesktopHelper.Views
{
    public partial class ScreenCaptureWindow : Window
    {
        private bool _isSelecting;
        private System.Windows.Point _startPoint;
        private System.Windows.Point _endPoint;
        private Bitmap? _screenCapture;

        public event EventHandler<ScreenshotTakenEventArgs>? ScreenshotTaken;

        public ScreenCaptureWindow()
        {
            InitializeComponent();
            CaptureScreen();
            SetupWindow();
        }

        private void CaptureScreen()
        {
            try
            {
                var bounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
                _screenCapture = new Bitmap(bounds.Width, bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                
                using var graphics = Graphics.FromImage(_screenCapture);
                graphics.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy);
                
                // 转换为WPF图像源
                var bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    _screenCapture.GetHbitmap(),
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());
                
                BackgroundImage.Source = bitmapSource;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"截取屏幕失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
                Close();
            }
        }

        private void SetupWindow()
        {
            // 全屏显示
            WindowState = WindowState.Maximized;
            WindowStyle = WindowStyle.None;
            Topmost = true;
            
            // 设置光标
            Cursor = Cursors.Cross;
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _isSelecting = true;
            _startPoint = e.GetPosition(this);
            _endPoint = _startPoint;
            
            SelectionRectangle.Visibility = Visibility.Visible;
            UpdateSelectionRectangle();
            
            CaptureMouse();
        }

        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isSelecting)
            {
                _endPoint = e.GetPosition(this);
                UpdateSelectionRectangle();
            }
        }

        private void Window_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (_isSelecting)
            {
                _isSelecting = false;
                ReleaseMouseCapture();
                
                CaptureSelectedArea();
            }
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                Close();
            }
        }

        private void Window_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            Close();
        }

        private void UpdateSelectionRectangle()
        {
            var left = Math.Min(_startPoint.X, _endPoint.X);
            var top = Math.Min(_startPoint.Y, _endPoint.Y);
            var width = Math.Abs(_endPoint.X - _startPoint.X);
            var height = Math.Abs(_endPoint.Y - _startPoint.Y);

            System.Windows.Controls.Canvas.SetLeft(SelectionRectangle, left);
            System.Windows.Controls.Canvas.SetTop(SelectionRectangle, top);
            SelectionRectangle.Width = width;
            SelectionRectangle.Height = height;
        }

        private void CaptureSelectedArea()
        {
            try
            {
                var left = Math.Min(_startPoint.X, _endPoint.X);
                var top = Math.Min(_startPoint.Y, _endPoint.Y);
                var width = Math.Abs(_endPoint.X - _startPoint.X);
                var height = Math.Abs(_endPoint.Y - _startPoint.Y);

                if (width < 10 || height < 10)
                {
                    Close();
                    return;
                }

                if (_screenCapture != null)
                {
                    var captureRect = new Rectangle(
                        (int)left, (int)top, (int)width, (int)height);
                    
                    var croppedBitmap = new Bitmap((int)width, (int)height);
                    using var graphics = Graphics.FromImage(croppedBitmap);
                    graphics.DrawImage(_screenCapture, 0, 0, captureRect, GraphicsUnit.Pixel);

                    // 触发截图完成事件
                    var args = new ScreenshotTakenEventArgs
                    {
                        Screenshot = croppedBitmap,
                        PinToDesktop = Keyboard.Modifiers.HasFlag(ModifierKeys.Control)
                    };
                    
                    ScreenshotTaken?.Invoke(this, args);
                }
                
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"截图失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
                Close();
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            _screenCapture?.Dispose();
            base.OnClosed(e);
        }
    }
}